<template>
  <div class="chatpannel">

    <ChatHeader :title="name"></ChatHeader>

    <ChatShowPanel :messages="messages" />

    <div class="input_panel">
      <el-input v-model="input" placeholder="" @keydown.enter.prevent="sendMessage" />
      <el-button @click="sendMessage">发送</el-button>
    </div>

  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import ChatShowPanel, { type ChatShowItem as ChatShowItemType } from './components/ChatShowPanel.vue';
import ChatHeader from './components/header/ChatHeader.vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useMessageStore } from '@/stores/messageStore';
import { getUserByIdApi } from '@/api/user';
const userStore = useUserStore();
const route = useRoute();
const name = ref(route.params.id as string);
const input = ref();
const messages = ref<Array<ChatShowItemType>>([]);
const messageStore = useMessageStore();

const targetId = ref(route.params.id as unknown as number);
const targetName = ref();

const sendMessage = () => {
  if (input.value) {
    messages.value.push(buildMessage(1, true, userStore.nick, `http://q1.qlogo.cn/g?b=qq&nk=3536370493&s=100`, input.value));

    //发送消息后更新/创建Message
    messageStore.messageList.push({
      userId: targetId.value,
      nick: '默认',
      content: input.value,
      avatar: '默认',
      time: '现在',
      unreadCount: 0,
    });

    input.value = ''
  }
}

const buildMessage = (id: number, isSelf: boolean, userName: string, avatar: string, content: string) => {
  return {
    userId: id,
    isSelf: isSelf,
    userName: userName,
    avatar: avatar,
    content: content,
  } as ChatShowItemType;
}

const getUserById = async () => {
  try {
    const result = await getUserByIdApi(targetId.value);
    if (result.code === 1) {
      targetName.value=result.data.nick
    }
  } catch (e) {
    console.log(e);
  }
}

const init = () => {
  getUserById();
}

init();
</script>

<style lang="scss" scoped>
.chatpannel {
  display: flex;
  flex-flow: column;
  height: 95%;

  .input_panel {
    display: flex;
    padding: 10px;
    flex-shrink: 0;
    gap: 5px;

    :deep(.el-input .el-input__wrapper) {
      border-radius: 0px;
    }
  }
}
</style>
